package com.atgugui.eduservice.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.atgugui.commonutils.ResultCode;
import com.atgugui.eduservice.client.VodServiceClient;
import com.atgugui.eduservice.entity.EduCourse;
import com.atgugui.eduservice.entity.EduCourseDescription;
import com.atgugui.eduservice.entity.vo.CourseInfoVo;
import com.atgugui.eduservice.entity.vo.CoursePublishVo;
import com.atgugui.eduservice.entity.vo.front.CompletedCourseInfo;
import com.atgugui.eduservice.entity.vo.front.QueryFrontCourseVo;
import com.atgugui.eduservice.mapper.EduCourseMapper;
import com.atgugui.eduservice.service.EduChapterService;
import com.atgugui.eduservice.service.EduCourseDescriptionService;
import com.atgugui.eduservice.service.EduCourseService;
import com.atgugui.eduservice.service.EduVideoService;
import com.atgugui.servicebase.exceptionhandler.GuLiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-08-29
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService; // 处理课程描述信息

    @Autowired
    private EduVideoService eduVideoService;

    @Autowired
    private EduChapterService eduChapterService;


    /**
     * 添加课程信息
     * 课程基本信息 + 课程描述
     * 上述两个信息之间的关系：one to one(通过主键关联，但是不使用外键进行关联，因为不好维护，这里的关联式逻辑上的关联)
     * @param courseInfoVo
     */
    @Override
    public String addCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse(); // 封装课程基本信息
        BeanUtils.copyProperties(courseInfoVo,eduCourse); // 从组合信息中抽取出基本信息，进行封装
        int insert = baseMapper.insert(eduCourse);// 保存到数据库中
        if (insert <= 0) {
            throw new GuLiException(20001,"课程信息添加失败");
        }
        String cid = eduCourse.getId(); // 获取基本信息中的主键id，描述信息中的主键id和它一致来实现一对一关联
        EduCourseDescription eduCourseDescription = new EduCourseDescription(); // 封装课程的描述信息
        BeanUtils.copyProperties(courseInfoVo,eduCourseDescription);
        eduCourseDescription.setId(cid);
        eduCourseDescriptionService.save(eduCourseDescription); // 保存描述信息到数据库中
        return cid; // 返回课程对象的id信息，传递给前端，以便做修改操作
    }

    @Override
    public CourseInfoVo getCourseInfoById(String courseId) {
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        // 查询课程信息
        EduCourse eduCourse = baseMapper.selectById(courseId);
        BeanUtils.copyProperties(eduCourse,courseInfoVo); // 封装课程信息到VO中

        // 查询课程的描述信息
        EduCourseDescription eduCourseDescription = eduCourseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(eduCourseDescription.getDescription());
        return courseInfoVo;
    }

    /**
     *注意：这里有一个小坑，更新操作是需要使用updateById，而不是update
     * update会将所有的数据进行更新，updateById会根据id值进行修改
     * @param courseInfoVo
     */
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        // 更新课程信息
        EduCourse eduCourse = new EduCourse(); // 课程信息
        BeanUtils.copyProperties(courseInfoVo,eduCourse); // 封装更新之后的课程信息
        int update = baseMapper.updateById(eduCourse);// 更新
        if (update == 0) {
            throw new GuLiException(ResultCode.ERROR,"更新课程信息失败");
        }

        // 更新课程描述
        EduCourseDescription eduCourseDescription = new EduCourseDescription(); // 课程描述信息
        eduCourseDescription.setId(courseInfoVo.getId());
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        boolean update1 = eduCourseDescriptionService.updateById(eduCourseDescription);
        if (!update1) {
            throw new GuLiException(ResultCode.ERROR,"更新课程描述信息失败");
        }
    }

    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    @Override
    public void removeCourseById(String courseId) {
        // 删除课程小节
        eduVideoService.removeVideoByCourseId(courseId);

        // 删除课程章节
        eduChapterService.removeChapterByCourseId(courseId);

        // 删除课程描述
        eduCourseDescriptionService.removeDescriptionByCourseId(courseId);

        // 删除课程本身
        int result = baseMapper.deleteById(courseId);

        if (result == 0) {
            throw new GuLiException(ResultCode.ERROR,"删除课程失败");
        }
    }

    @Override
    public HashMap<String, Object> getFrontCoursePageList(Page<EduCourse> coursePage, QueryFrontCourseVo queryFrontCourseVo) {
        //2 根据讲师id查询所讲课程
        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，不为空拼接
        if(!StringUtils.isEmpty(queryFrontCourseVo.getSubjectParentId())) { //一级分类
            wrapper.eq("subject_parent_id",queryFrontCourseVo.getSubjectParentId());
        }
        if(!StringUtils.isEmpty(queryFrontCourseVo.getSubjectId())) { //二级分类
            wrapper.eq("subject_id",queryFrontCourseVo.getSubjectId());
        }
        if(!StringUtils.isEmpty(queryFrontCourseVo.getBuyCountSort())) { //关注度
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(queryFrontCourseVo.getGmtCreateSort())) { //最新
            wrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(queryFrontCourseVo.getPriceSort())) {//价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(coursePage,wrapper);

        List<EduCourse> records = coursePage.getRecords();
        long current = coursePage.getCurrent();
        long pages = coursePage.getPages();
        long size = coursePage.getSize();
        long total = coursePage.getTotal();
        boolean hasNext = coursePage.hasNext();//下一页
        boolean hasPrevious = coursePage.hasPrevious();//上一页

        //把分页数据获取出来，放到map集合
        HashMap<String, Object> map = new HashMap<>();
        map.put("items", records); // 分页数据
        map.put("current", current); // 当前页索引
        map.put("pages", pages); // 总页数
        map.put("size", size); //
        map.put("total", total); // 数据的总条数
        map.put("hasNext", hasNext); // 是否还有下一页
        map.put("hasPrevious", hasPrevious); // 是否还有上一页

        //map返回
        return map;
    }

    @Override
    public CompletedCourseInfo getCompleteCourseInfo(String courseId) {
        return baseMapper.getCompleteCourseInfoByCourseId(courseId);
    }
}
